<template>
  <div>
    <!-- <br><br class="hidden-xs">
    <div class="row hidden-xs">

    </div>
    <br><br class="hidden-xs"> -->
    <div class="view-list row">
      <el-row style="padding:0 1%">
        <el-col :span="5">
          <el-card>
            <div style="display:flex">
              <el-input v-model="input"
                        placeholder="请输入姓名"></el-input>
              <el-button type="primary"
                         size="small"
                         @click="nameChange()">搜索</el-button>
              <el-button type="success"
                         plain
                         size="small"
                         @click="nameClean()">重置</el-button>
            </div>
            <div v-loading="menuLoading"
                 class="menu_div split_menu">
              <el-menu default-active="2"
                       class="el-menu-vertical-demo"
                       @select="handleOpen"
                       @close="handleClose">
                <div v-for="(item,index) in groupList"
                     :key="item.g_id">
                  <el-submenu :index="index+''">
                    <template slot="title">
                      <i class="el-icon-plus"></i>
                      <span>{{ item.g_name }}</span>
                      <span>({{ item.online }}/{{ item.num }})</span>
                    </template>
                    <div v-for="(k,i) in item.member"
                         :key="k.device_id">
                      <el-menu-item-group>
                        <el-menu-item :index="index+'-'+i">
                          <i class="el-icon-s-custom" />
                          <span>{{ k.nick }}</span>
                          <span class="member_state"
                                :style="{color:k.on_line===0?'red':'green'}">{{ k.on_line===0?'离线':'在线' }}</span>
                        </el-menu-item>
                      </el-menu-item-group>
                    </div>
                  </el-submenu>

                </div>
              </el-menu>
            </div>
          </el-card>
        </el-col>
        <el-col :span="19">
          <el-card>
            <div class="text-center">
              <el-button-group class="player-btn-group">
                <el-button v-for="list in playerBtnGroup"
                           :key="list.num"
                           size="medium"
                           :class="{'active' : playerLength == list.num}"
                           @click.prevent="setPlayerLength(list.num)">{{ list.name }}</el-button>
                <!-- <el-button id="full-btn-medium"
                           size="medium"
                           title="全屏显示"
                           @click.prevent="fullscreen"><i class="el-icon-full-screen"></i></el-button> -->
              </el-button-group>
            </div>
            <div class="video"
                 style="height:700px;padding:0 1%;">
              <div v-for="(item,index) in players"
                   :key="index"
                   class="live_player_div"
                   :class="{'active': index == playerIdx}"
                   :style="{width:playerLength==1?'100%':playerLength==4?'50%':playerLength==9?'33.333%':playerLength==16?'25%':'',height:playerLength==1?'100%':playerLength==4?'50%':playerLength==9?'33.3%':playerLength==16?'25%':''}"
                   @click="clickPlayer(index)">
                <LivePlayer :videoUrl="item.videoUrl"
                            :poster="item.poster"
                            :controls="item.bControls"
                            :loading.sync="item.bLoading"
                            live
                            muted
                            stretch
                            autoplay
                            aspect="fullscreen"
                            element-loading-text="加载中..."
                            element-loading-background="#000"
                            @message="$message">
                </LivePlayer>
                <div v-show="item.videoUrl"
                     class="video-close">
                  <div class="video_title">{{ item.device_name }}</div>
                  <div class="video_close_title"
                       @click="closeVideo(index)">关闭</div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <br><br class="hidden-xs">
  </div>
</template>
<script>
import LivePlayer from '@liveqing/liveplayer'
import axios from 'axios'
export default {
  components: {
    LivePlayer
  },
  data() {
    return {
      bSmartStream: '',
      videoUrlVisible: false,
      videoIndex: 0,
      input: '',
      players: [],
      playerLength: 4,
      loadedData: false,
      playerIdx: 0,
      level: 0,
      localData: {
        num1: {},
        num4: {},
        num9: {},
        num16: {}
      },
      serverInfo: null,
      userInfo: null,
      activeName: 'first',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      videoList: [],
      videoData: null,
      websock: null,
      personData: {
        username: 'rj_aqm', // rjgf_test
        pwd: '123456',
        pkey: '',
        access_token: ''
      },
      safety: {
        adminId: '',
        videoDate: '',
        userId: '',
        userName: '',
        realName: ''
      },
      deviceOnline: false,
      capsUrl: 'https://caps.runde.pro/api/',
      groupList: [],
      originalGroupList: [],
      groupList2: [],
      groupList3: [],
      menuLoading: false
    }
  },
  computed: {
    playerBtnGroup() {
      var list = [{
        num: 1,
        name: '单屏'
      }, {
        num: 4,
        name: '四分屏'
      }, {
        num: 9,
        name: '九分屏'
      },
      {
        num: 16,
        name: '十六分屏'
      }]
      return list
    }
  },
  created() {
    if (this.websock) {
      this.websock.close() // 关闭websocket连接
    }
  },
  mounted() {
    this.setPlayerLength(4)
    // this.getByEquipmentId(9272)
    this.initCapsLogin()
  },
  methods: {
    handleClick() {

    },
    handleNodeClick() {

    },
    getByEquipmentId(id) {
      this.$get('console/equipmentMonitorSettings/getByEquipmentId', {
        equipmentId: id
      }).then(res => {
        if (res.data) {
          this.videoList = JSON.parse(res.data.layout)
        }
      })
    },
    openVideo(data) {
      this.players[this.playerIdx] = { ...data }
      this.videoData = data
    },
    setPlayerLength(len) {
      if (len == this.players.length) {
        return
      }
      // this.clearVideos();
      this.players = []
      this.playerLength = len
      for (var i = 0; i < len; i++) {
        this.players.push({
          serial: '',
          code: '',
          videoUrl: '',
          protocol: '',
          poster: '', // 视频封面图片 String default ''
          bLoading: true, // 指示加载状态, 支持 sync 修饰符
          bCloseShow: true,
          bControls: true, // 显示播放器控制栏 Boolean default true
          bSmart: true,
          bFullscreen: true,
          closeTimer: 0,
          device_id: '',
          device_name: ''
        })
      }
    },
    clickPlayer(index) {
      this.playerIdx = index
    },
    talkStart(e) {

    },
    ptzControl(e) {

    },
    selectChannel(i) {
      this.videoIndex = i + 1
      this.videoUrlVisible = true
    },
    handleClose() { },
    initCapsLogin() {
      this.menuLoading = true
      axios({
        method: 'post',
        url: this.capsUrl + 'index.php?ctl=tool&act=get_pkey',
        data: { user_name: this.personData.username, pwd: this.personData.pwd }
      }).then((res) => {
        if (res.data.status) {
          this.personData.pkey = res.data.data
          this.initCapsToken()
        }
      }).catch(err => { console.log(err) })
    },
    initCapsToken() {
      axios({
        method: 'post',
        url: this.capsUrl + 'index.php?ctl=tool&act=get_token',
        data: { user_name: 'rjgf_test', pkey: this.personData.pkey }
      }).then((res) => {
        if (res.data.status) {
          // var key = res.data.data
          this.personData.access_token = res.data.session_id
          this.initWebSocket()
        }
      }).catch(err => { console.log(err) })
    },
    initWebSocket() {
      if (typeof WebSocket === 'undefined') {
        alert('您的浏览器不支持WebSocket')
        return false
      }
      // wss://caps.runde.pro/wss wss://caps.runjian.com/wss
      const wsuri = 'wss://caps.runde.pro/wss' // websocket地址

      this.websock = new WebSocket(wsuri)
      this.websock.onopen = this.websocketonopen
      this.websock.onmessage = this.websocketonmessage
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen() {
      // 连接成功
      console.log('WebSocket连接成功')
      const actions = { act: 'ma_login', user_name: this.personData.username, access_token: this.personData.access_token }
      this.websock.send(JSON.stringify(actions))
    },
    // 接收后端返回的数据，可以根据需要进行处理
    websocketonmessage(e) {
      const self = this
      const dataJson = JSON.parse(e.data)
      // console.log(dataJson)
      if (dataJson.cmd === 'ma_login' && dataJson.status) {
        this.safety.adminId = dataJson.admin_info.admin_id
        this.initCapsGrouping()
        // 长链接连接成功
        // 添加心跳检测，每30秒发一次数据，防止连接断开（这跟服务器的设置有关，如果服务器没有设置每隔多长时间不发消息断开，可以不进行心跳设置）
        try {
          this.timer = setInterval(() => {
            try {
              self.websock.send(JSON.stringify({ act: 'ma_get_active_devices' }))
              // console.log('发送心跳消息')
            } catch (err) {
              console.log('断开了：' + err)
              // self.connection()
            }
          }, 5000)
        } catch (error) {
          console.log(error)
        }
      }
      // 发送心跳成功
      if (dataJson.cmd === 'ma_get_active_devices') {
        // 用户id

        if (dataJson.status) {
          this.safety.userName = dataJson.data[0].user_info.user_name
        }
      }
      if (dataJson.cmd === 'ma_open_rtsp' && dataJson.status) {
        this.players[this.playerIdx].videoUrl = dataJson.play_url[2]
        this.deviceOnline = true
      }
    },
    initCapsGrouping() {
      var ceilNum = this.ceil()
      axios({
        method: 'post',
        url: this.capsUrl + 'index.php?ctl=bruce&act=get_group_list_v2',
        data: { admin_id: this.safety.adminId, udid: ceilNum }
      }).then((res) => {
        if (res.data.status) {
          // this.GroupList
          this.groupList2 = res.data.data
          this.groupList2.forEach((e, index) => {
            this.initCapsGroupMember(e, index)
          })
        }
      }).catch(err => { console.log(err) })
    },
    initCapsGroupMember(e, index) {
      axios({
        method: 'post',
        url: this.capsUrl + 'index.php?ctl=bruce&act=get_group_member_list',
        data: { admin_id: this.safety.adminId, g_id: e.g_id }
      }).then((res) => {
        if (res.data.status) {
          // this.GroupList.push({ ...e })
          this.groupList2[index]['member'] = res.data.data
        }
        if (index == this.groupList2.length - 1) {
          this.groupList = this.groupList2
          this.originalGroupList = JSON.parse(JSON.stringify(this.groupList2))
          this.menuLoading = false
          console.log(this.groupList)
        }
      }).catch(err => { console.log(err) })
    },
    // 连接建立失败重连
    websocketonerror(e) {
      console.log(`连接失败的信息：`, e)
      this.initWebSocket() // 连接失败后尝试重新连接
    },
    // 关闭连接
    websocketclose(e) {
      console.log('断开连接', e)
    },
    random(min, max) {
      return Math.floor(Math.random() * (max - min)) + min
    },
    ceil() {
      var data = ''
      for (let index = 0; index < 32; index++) {
        var str = Math.ceil(Math.random() * 10)
        data += str
      }
      return data
    },
    handleOpen(key) {
      var k = key.split('-')
      var data = this.groupList[k[0]].member[k[1]]
      this.players[this.playerIdx].device_id = data.device_id
      this.players[this.playerIdx].device_name = data.g_name + '_' + data.nick
      this.websock.send(JSON.stringify({ act: 'ma_open_rtsp', device_id: data.device_id }))
    },
    closeVideo(i) {
      this.websock.send(JSON.stringify({ act: 'ma_stop_rtsp', device_id: this.players[i].device_id }))
      this.players[i].videoUrl = ''
    },
    nameChange() {
      this.menuLoading = true
      var data = []
      var data2 = []
      this.originalGroupList.forEach(x => {
        if (x.member) {
          x.member.forEach(y => {
            if (y.nick.indexOf(this.input) != -1) {
              data.push(y)
            }
          })
          if (data.length > 0) {
            x.member = data
            data2.push(x)
            data = []
          }
        }
      })
      this.groupList = []
      setTimeout(() => {
        this.groupList = data2
        this.menuLoading = false
      }, 1000)
    },
    nameClean() {
      this.input = ''
      this.groupList = this.originalGroupList
    }
  }
}
</script>
<style lang="scss" scoped>
.player-btn-group {
  .active {
    background-color: #404d59;
    color: #ffffff;
  }
}
.live_player_div {
  float: left;
  border: 1px solid #fff;
  position: relative;
}
.video_list_button {
  padding: 10px 0 10px 20px;
  background: #fff;
  border-radius: 7px;
  font-size: 16px;
  margin-bottom: 5px;
  cursor: pointer;
}
.video_list_button:hover {
  background: #78cdff;
}
.button_hover {
  background: #78cdff;
  color: #fff;
}
.active {
  border: 2px solid red;
}
.settings-block {
  margin: 30px auto;
  text-align: center;
}
.ptz-block {
  width: 150px;
  height: 180px;
  margin: 0 auto;
  text-align: center;
  position: relative;
  font-size: 24px;

  .ptz-cell {
    width: 50px;
    height: 50px;
    line-height: 50px;
    position: absolute;
  }

  .ptz-cell.active {
    color: #ccc;
    font-size: 26px;
  }
  .ptz-cell.readonly {
    color: #ddd;
  }
  .fa-microphone,
  .fa-microphone-slash {
    padding: 10px 13px;
    border-radius: 25px;
  }
  .fa-microphone.active {
    color: #fff;
  }
  .fa-microphone.readonly {
    color: #ddd;
  }
  .fa-microphone-slash.readonly {
    color: #ddd;
  }
  .mic-level-bar {
    position: absolute;
    transform: rotate(-90deg);
    width: 100%;
    top: 70px;
    left: -80px;
  }

  .ptz-center {
    top: 50px;
    left: 50px;
    border-radius: 25px;
    background-color: #ccc;
  }

  .ptz-up {
    top: 0;
    left: 50px;
  }

  .ptz-left {
    top: 50px;
    left: 0;
  }

  .ptz-right {
    top: 50px;
    left: 100px;
  }

  .ptz-down {
    top: 100px;
    left: 50px;
  }

  .ptz-zoomin {
    top: 150px;
    left: 20px;
  }

  .ptz-zoomout {
    top: 150px;
    left: 80px;
  }

  .ptz-up,
  .ptz-left,
  .ptz-right,
  .ptz-down,
  .ptz-center > .fa-microphone,
  .ptz-zoomin,
  .ptz-zoomout {
    cursor: pointer;

    &.readonly {
      cursor: auto;
    }
  }
}
.video-close {
  position: absolute;
  top: 5px;
  right: 5px;
  color: white;
  font-size: 12px;
  padding: 2px 5px;
  width: 100%;
}
.video_close_title {
  float: right;
  cursor: pointer;
  padding: 5px;
  border-radius: 10px;
  background: #7e7e7e99;
}
.text-center {
  margin-bottom: 20px;
}
.el-menu {
  height: 100%;
  overflow: auto;
}

.view-list {
  height: 82vh;
}
.menu_div {
  height: 77vh;
}
.el-submenu__title {
  color: #000 !important;
  i {
    color: #000 !important;
  }
  span {
    color: #000 !important;
  }
}
.member_state {
  float: right;
}
.el-menu-item {
  color: #000 !important;
}
.el-menu-item.is-active {
  background: #dedede47;
  color: #409eff !important;
}
.video_title {
  float: left;
  padding: 5px;
  background: #7e7e7e99;
  border-radius: 10px;
  display: block;
  float: left;
}
</style>
<style>
.split_menu .el-submenu__title i {
  color: #000 !important;
}
</style>
